package edu.must.uh.Generator;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

public class JavaServletFileUtils {
    
    /**
     * 更新表结构
     */
    public static void updateJavaPOFile(){
        Map<String,TableInfo>tables=TableContext.tables;
        for(TableInfo tableInfo:tables.values()){
            createJavaPoFile(tableInfo,new MySQLTypeConvertor());
        }
    }    

    /**
                   * 根据表信息生成java源码
     * @param tableInfo 表信息
     * @param convertor 数据类型转换器
     * @return  java类的源代码
     */
    private static String createJavaSrc(TableInfo tableInfo,TypeConvertor convertor){
       
        Map<String,ColumnInfo>columns=tableInfo.getColumns();
        List<String> javaFields=new ArrayList<>();
        for (ColumnInfo columnInfo:columns.values()){           
            javaFields.add(columnInfo.getName());
        }
        String javaFieldString= javaFields.toString();
        javaFieldString = javaFieldString.replace("[", "").replace("]", "");        
        StringBuilder src=new StringBuilder();
        //生成package语句
        src.append("package "+ DBHepler.getConf().getPoPackage()+".servlet;\n");
        
        String classnameString = StringUtils.underlineToBigCamel(tableInfo.getTname());
        //生成import语句
        src.append("\r\n" + 
                "import java.util.List;\r\n" + 
                "import java.util.Map;\r\n" + 
                "import javax.servlet.annotation.WebServlet;\r\n" + 
                "import javax.servlet.http.HttpServletRequest;\r\n" + 
                "import javax.servlet.http.HttpServletResponse;\r\n" + 
                "import edu.must.uh.bean."+classnameString+";\r\n" + 
                "import edu.must.uh.impl."+classnameString+"Impl;\r\n" + 
                "import edu.must.uh.util.R;\r\n" + 
                "import edu.must.uh.util.ServletUtils;\r\n" + 
                "import edu.must.uh.util.Tools;\r\n" + 
                "import edu.must.uh.util.ToolsOfString; \n");
         
        src.append(" \n \n \n");        
        
        //生成类声明语句
        src.append(" @WebServlet(\"/"+StringUtils.underlineToBigCamel(tableInfo.getTname())+"Servlet\") \n"); 
        src.append("public class "+StringUtils.underlineToBigCamel(tableInfo.getTname())+"Servlet  extends  BaseServlet {\n \n");
        
        src.append(" private static final long serialVersionUID = 1L; \n"); 
        src.append( classnameString+"Impl i"+classnameString+"impl = new "+classnameString+"Impl(); \n");
        
        src.append(" public Object getTableJson(HttpServletRequest request, HttpServletResponse response) throws Exception \n");
        src.append(" { \n ");
        src.append("    i"+classnameString+"impl._PageBean =pageBean; \n");
        src.append("    Map<String, Object> searchcondition = ServletUtils.getsearchcondition(request); \n");        
        src.append("   List<Map<String, Object>>  data = i"+classnameString+"impl.getList(searchcondition,\"\");\n ");
        src.append("   return R.succ(data); \n");
        src.append(" }  "); 
        src.append(" \n \n \n");
        
        
        src.append(" public Object saveForm(HttpServletRequest request, HttpServletResponse response) throws Exception \n"); 
        src.append(" { \n "); 
        src.append("   String keyValue = ToolsOfString.conveString(request.getParameter(\"keyValue\")); \n"); 
        src.append("   "+classnameString+" bean = new "+classnameString+"(); \n"); 
        src.append("     if(Tools.notEmpty(keyValue))  { \n");
        src.append("      bean.set"+tableInfo.getOnlyPriKey().getName()+"(Tools.getUUID32()); \n");
        src.append("     } \n");
        src.append("    Integer ires = i"+classnameString+"impl.save(bean) ;\n");
        src.append("    if(ires == 0) { \n");
        src.append("      return R.fail(); \n"); 
        src.append("    } else { \n");
        src.append("      return R.succ(); \n"); 
        src.append("    }  \n"); 
        src.append(" }  \n"); 
        src.append(" \n \n \n");       
        
        
        
        src.append(" public Object getFormEntity(HttpServletRequest request, HttpServletResponse response) throws Exception \n"); 
        src.append(" { \n "); 
        src.append("   Map<String, Object> searchcondition = ServletUtils.getsearchcondition(request); \n"); 
        src.append("   List<Map<String, Object>>  data = i"+classnameString+"impl.getList(searchcondition,\"\");  \n");
        src.append("   Map<String, Object> resdata = null; \n");
        src.append("   if(data.size() == 1) { \n");
        src.append("      resdata =data.get(0); \n");
        src.append("    } \n"); 
        src.append("    return R.succ(resdata); } \n");     
        src.append(" \n \n \n");
        
        
        
        src.append(" public Object delForm(HttpServletRequest request, HttpServletResponse response) throws Exception \n"); 
        src.append(" { \n "); 
        src.append("   String keyValue = ToolsOfString.conveString(request.getParameter(\"value\")); \n"); 
     
        src.append("    Integer ires = i"+classnameString+"impl.delete(keyValue) ;\n");
        src.append("    if(ires == 1) { \n");
        src.append("       return R.succ(); \n"); 
        src.append("    } else { \n");
        src.append("      return R.fail(); \n"); 
        src.append("    }  \n"); 
        src.append(" }  \n"); 
        src.append(" \n \n \n");
 
        //生成结束符
        src.append("}");
        return src.toString();
    }

    /**
     * 生成java文件
     * @param tableInfo 表信息
     * @param convertor 类型转换器
     */
    private static void createJavaPoFile(TableInfo tableInfo,TypeConvertor convertor){
      
        String srcPath=DBHepler.getConf().getSrcPath()+"/";
        //将包名转换为文件名，然后和srcPath拼接
        String packagePath=DBHepler.getConf().getPoPackage().replace(".","/")+"/Servlet";
        File f=new File(srcPath+packagePath);
        if (!f.exists()){
            f.mkdirs();
        }
        BufferedWriter bw=null;
        try {
            String filePth = f.getAbsoluteFile()+"/"+StringUtils.underlineToBigCamel(tableInfo.getTname())+"Servlet.java";
            File file2 = new File(filePth);
            if(file2.exists()) {
                return ;
            }
            //获取源码
            String src=createJavaSrc(tableInfo,convertor);
            //将源码写入文件
            bw=new BufferedWriter(new FileWriter(filePth));
            bw.write(src);
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            if (bw!=null){
                try {
                    bw.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

  
}
